#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, yaml
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class EcsHandler(webapp.RequestHandler):
  def __init__(self):
    self.config = yaml.safe_load(
      open(
        os.path.join(os.path.dirname(__file__), 'ecs.yaml')
        ).read().decode('utf-8')
      )

  def get(self):
    id = self.request.get('id', default_value='index')
    if not id in self.config:
      self.response.set_status(404)
      self.response.out.write('404 Not found')
      return

    file = self.config[id]

    if not 'body' in file:
      self.response.set_status(404)
      self.response.out.write('404 Not found')
      return

    tmpl = template.Template(file['body'])
    ctx = template.Context({
      'app_url':
        self.request.application_url,
      'path_url':
        self.request.path_url,
      'associate_tag':
        self.request.get('associate_tag', default_value='ogawamemorand-22'),
      })

    if 'content-type' in file:
      self.response.headers['Content-Type'] = file['content-type']
    self.response.out.write(tmpl.render(ctx))

def main():
  application = webapp.WSGIApplication([
      ('/ecs', EcsHandler),
      ], debug=True)
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
